package io.sage.modules.socket.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import io.sage.common.utils.Change;
import io.sage.modules.socket.service.SocketClientService;

import javax.annotation.Resource;

/**
 * Created by Mafy on 2019/7/15.
 */
@Service("socketClientService")
public class SocketClientServiceImpl extends Thread implements SocketClientService{

    //定义一个Socket对象
    Socket socket = null;
    //写操作
    OutputStream os= null;

    @Value(value="${socket.serverIp}")
    private String host;

    @Value(value="${socket.serverPort}")
    private int port;

    @Value(value="${socket.isHeart}")
    private boolean isHeart;//是否开启心跳
    @Value(value="${socket.heartTime}")
    private int heartTime;//心跳时间

    private synchronized String init() {
        try {
            //需要服务器的IP地址和端口号，才能获得正确的Socket对象
            socket = new Socket(host,port);
            os= socket.getOutputStream();

            //todo 开启心跳
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(isHeart){
                        try {
                            sleep(heartTime);
                            sendMsg("00");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            if(socket.isClosed() || !socket.isConnected() || socket.isInputShutdown() || socket.isOutputShutdown()){
                                try {
                                    socket.close();
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                                init();
                            }
                        }
                    }
                }
            }).start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接服务器失败");
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 读取服务端返回的数据
     * 现在没用，如果发送数据是原路返回响应值，则使用，现在用socketserver里面的线程处理返回的数据
     */
    @Override
    public void run() {
        //客户端一连接就可以写数据个服务器了
        try {
            // 读Sock里面的数据
            if(ObjectUtils.isEmpty(socket)){
                init();
            }
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println("引用websocket返回頁面數據");
                String ind = "00000000000000000000";
                String buff = Change.byteArrayToHexString(buf);
                System.out.println(buff.split(ind)[0]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String sendMsg(String msg){
        try {
            if(ObjectUtils.isEmpty(socket)){
                init();
            }
            os.write(Change.HexString2Bytes(msg));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
